<template>
  <div class="posts">
    <!-- 面包屑导航区 -->
    <el-card class="breadcrumb-box">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item
          ><a href="/#/manager/home">首页</a></el-breadcrumb-item
        >
        <el-breadcrumb-item>帖子管理</el-breadcrumb-item>
      </el-breadcrumb>
    </el-card>

    <el-card class="post-list">
      <!-- 帖子列表 -->
      <el-table
        :data="postList"
        border
        style="width: 100%"
        v-loading="loading1"
      >
        <el-table-column
          type="index"
          width="60"
          align="center"
          label="序号"
        ></el-table-column>
        <el-table-column prop="title" align="center" label="标题" width="300">
        </el-table-column>
        <el-table-column
          prop="userName"
          align="center"
          label="发布者"
          width="140"
        >
        </el-table-column>
        <el-table-column prop="type" label="类型" align="center" width="70">
          <template #default="scope">
            <el-tag v-if="scope.row.type === 0">普通</el-tag>
            <el-tag v-else type="success">置顶</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="commentCount"
          align="center"
          label="评论数"
          width="70"
        >
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0">正常</el-tag>
            <el-tag v-if="scope.row.status === 3" type="warning"
              >管理员已删除</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          align="center"
          width="180"
        ></el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="140">
          <template #default="scope">
            <el-tooltip content="查看" placement="top" :enterable="false">
              <!-- 查看帖子按钮 -->
              <el-button
                type="success"
                :icon="View"
                @click="showPostDetailDialog(scope.row.postId)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              v-if="scope.row.status !== 3"
              content="删除"
              placement="top"
              :enterable="false"
            >
              <!-- 删除按钮 -->
              <el-button
                type="danger"
                :icon="Delete"
                @click="deletePost(scope.row.postId)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 15, 20, 30]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 查看帖子对话框 -->
    <el-dialog
      class="post-view"
      title="查看帖子"
      v-model="viewPostDialogVisible"
      width="70%"
      @close="resetPostDetail"
      style="text-align: left;"
    >
      <el-card
        v-loading="loading2"
        element-loading-text="Loading..."
        element-loading-background="#fff"
        style="text-align: left;"
      >
        <h1 v-html="postDetail.title"></h1>
        <div class="user-message">
          <el-avatar
            size="medium"
            :src="postDetail.userName === proxy.$storage.getItem('userInfo').userName ? 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png' : 'https://source.unsplash.com/random'"
          ></el-avatar>
          <span>{{ postDetail.userName }}</span>
          <span>{{ postDetail.createTime }}</span>
        </div>
        <el-tag v-for="(item, index) in postDetail.tags" :key="index">{{
          item
        }}</el-tag>
        <Editor
          style="min-height: 50px"
          v-model="postDetail.content"
          :defaultConfig="editorConfig"
          @onCreated="onCreated"
          mode="default"
        />
      </el-card>
      <span slot="footer" class="footer">
        <el-button @click="viewPostDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="viewPostDialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Editor } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';
import { ref, getCurrentInstance, ComponentInternalInstance, onMounted, reactive, onUnmounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { View, Delete  } from '@element-plus/icons-vue'

const { appContext } = getCurrentInstance() as ComponentInternalInstance;
const proxy = appContext.config.globalProperties;

// 帖子列表
const postList = ref([]);
// 获取帖子列表的页码参数对象
const queryInfo = reactive({
  // 当前的页数
  pageNum: 1,
  // 当前每页显示的数据条数
  pageSize: 10,
});
// 帖子列表总条数
const total = ref(0);
// 是否正在加载
const loading1 = ref(false);
const loading2 = ref(false);
// 是否显示查看帖子对话框
const viewPostDialogVisible = ref(false);
// 帖子详情
interface PostDetail {
  commentCount: Number
  comments: Object
  content: String
  createTime: String
  modules: []
  postId: Number
  status: Number
  tags: []
  title: String
  type: Number
  userId: Number
  userName: String
}
let postDetail = reactive<PostDetail>({
  commentCount: 0,
  comments: {},
  content: '',
  createTime: '',
  modules: [],
  postId: 0,
  status: 0,
  tags: [],
  title: '',
  type: 0,
  userId: 0,
  userName: ''
});
// 富文本编辑器实例
const editor = ref(null) as any;
const editorConfig = reactive({
  readOnly: true,
});

onMounted(() => {
  getPostList();
})

// 获取所有帖子
function getPostList() {
  loading1.value = true;
  proxy.$request.discussPost.allPosts(queryInfo).then((res: any) => {
    postList.value = res.data.list;
    total.value = res.data.total;
    loading1.value = false;
  });
};
// 监听 pagesize 改变
function handleSizeChange(newSize: any) {
  queryInfo.pageSize = newSize;
  getPostList();
};
// 监听页码值改变
function handleCurrentChange(newNum: any) {
  queryInfo.pageNum = newNum;
  getPostList();
};
// 获取帖子详情
function showPostDetailDialog(postId: any) {
  viewPostDialogVisible.value = true;
  loading2.value = true;
  proxy.$request.discussPost
    .detail({ postId: postId, pageNum: 0 })
    .then((res: any) => {
      postDetail = res.data;
      loading2.value = false;
    });
};
// 重置帖子详情信息
function resetPostDetail() {
  postDetail = {
    commentCount: 0,
    comments: {},
    content: '',
    createTime: '',
    modules: [],
    postId: 0,
    status: 0,
    tags: [],
    title: '',
    type: 0,
    userId: 0,
    userName: ''
  }
}
// 创建富文本编辑器实例对象
function onCreated(Editor: any) {
  editor.value = Object.seal(Editor); // 一定要用 Object.seal() ，否则会报错
};
// 删除帖子
function deletePost(postId: any) {
  ElMessageBox.confirm('此操作将删除帖子, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      proxy.$request.discussPost.removePost(postId).then((res: any) => {
        ElMessage({
          type: 'success',
          message: res.msg,
          duration: 1000,
        });
        getPostList();
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消操作',
        duration: 1000,
      });
    });
};

onUnmounted(() => {
  const Editor = editor.value;
  if (Editor === null) return;
  Editor.destroy(); // 组件销毁时，及时销毁编辑器
});
</script>

<style lang="less" scoped>
.breadcrumb-box {
  height: 36px;
  border-radius: 0;
  padding: 0 20px;
  border: 0;
  margin: 0 0 20px !important;
  position: fixed;
  top: 60px;
  width: 100%;
  z-index: 9;

  .el-breadcrumb {
    line-height: 36px;
  }

  /deep/ .el-card__body {
    padding: 0;
  }
}

.post-list {
  margin: 60px 20px 0;

  .el-pagination {
    margin-top: 20px;
    justify-content: center;
  }
}

.post-view {
  h1 {
    font-size: 25px;
    margin: 15px 0;
    font-weight: 700;
    text-align: center;
  }
  .user-message {
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    margin-bottom: 10px;

    .el-avatar {
      float: left;
    }

    span:nth-child(2) {
      font-size: 20px;
      margin: 0 12px;
      color: #555666;
    }

    span:nth-child(3) {
      color: #777888;
    }
  }
  .el-tag {
    margin: 10px 15px 10px 0;
  }
  .footer{
    display: flex;
    justify-content: end;
    width: 100%;
    margin-top: 20px;
  }
}
</style>
